<!--
 * @Author: your name
 * @Date: 2021-09-01 16:03:37
 * @LastEditTime: 2021-09-01 16:05:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bigdate\src\views\admin\componentsPage\chartsPage.vue
-->
<template>
  <div :style="width">
    <component :is="tag" ref="codeRef"></component>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  onMounted,
  PropType,
  ref,
  unref,
  watch,
} from "@vue/runtime-core";
import { toQrCode, ConfigOptions, downloadCode } from "./toqrcode";
import { toDataURL } from "qrcode";
interface propArgs {
  tag: String;
  value: String;
  options: ConfigOptions;
  content: String;
  width?: Number;
}
export default defineComponent({
  name: "qrcode",
  props: {
    //   标签类型
    tag: {
      type: String as PropType<"canvas" | "img">,
      default: () => "img",
    },
    //    其他参数 比如颜色等
    options: {
      type: Object as PropType<ConfigOptions>,
      default: () => {},
    },
    //   内容
    content: {
      type: String,
      default: () => "http://120.76.142.67:3000/",
    },
    //   宽度
    width: {
      type: Number,
      default: () => 200,
    },
  },
  setup(prop) {
    const { tag } = prop;
    const codeRef = ref<HTMLCanvasElement | HTMLImageElement | null>(null);
    // 监听参数变化
    watch(()=>prop.content,()=>{
          createCode();
    })
    onMounted(() => {
        createCode()
    });
    // 生成二维码
    const createCode = ()=>{
        const codeEl = unref(codeRef);
      if (codeEl && tag == "canvas") {
        const url: Promise<String> = toQrCode({
          canvas: codeEl,
          width: prop.width,
          content: prop.content,
          options: prop.options,
        });
      }
      if (tag == "img") {
        toDataURL(prop.content, {
          errorCorrectionLevel: "H",
          width: prop.width,
          options: prop.options,
        }).then((res: any) => {
          codeEl.src = res;
        });
      }
      // 添加样式
      Object.assign(codeRef.value?.style ?? {}, {
        width: prop.width + "px",
        height:prop.width + "px",
      });
    }
    // 在外部使用ref调用
    const downloadCodes = () => {
      const codeEl = unref(codeRef);
      downloadCode(codeEl.src);
    };
    return {
      codeRef,
      createCode,
      downloadCodes,
    };
  },
});
</script>